package com.dream.testtubebaby.data.product;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

import com.dream.testtubebaby.utils.DBHelper;

public class ShopCartDao {
	private DBHelper dbHelper;

	public ShopCartDao(Context context) {
		dbHelper = DBHelper.getInstance(context);
	}
	//product_id integer , iconurl text , product_name text , product_price integer , product_num integer , product_dec text
	public void add(ShoppingCartItemData newsItem) {
		String sql = "insert into tb_spctItem (product_id,iconurl,product_name,product_price,product_num,product_dec) values(?,?,?,?,?,?) ;";
		SQLiteDatabase db = dbHelper.getWritableDatabase();
		db.execSQL(
				sql,
				new Object[] { newsItem.getProduct_id(), newsItem.getIconUrl(),
						newsItem.getProduct_name(), newsItem.getProduct_price(),
						newsItem.getProduct_num(), newsItem.getProduct_dec() });
		db.close();
	}

	public void deleteAll() {
		try {
			String sql = "delete from tb_spctItem";
			SQLiteDatabase db = dbHelper.getWritableDatabase();
			db.execSQL(sql);
			db.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	public void deleteOneProduct(long product_id){
		try {
			String sql = "delete from tb_spctItem where product_id = " + product_id;
			SQLiteDatabase db = dbHelper.getWritableDatabase();
			db.execSQL(sql);
			db.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public void add(List<ShoppingCartItemData> newsItems) {
		for (ShoppingCartItemData newsItem : newsItems) {
			add(newsItem);
		}
	}

	public List<ShoppingCartItemData> list() {
		List<ShoppingCartItemData> newsItems = new ArrayList<ShoppingCartItemData>();
		try {
			String sql = "select product_id,iconurl,product_name,product_price,product_num,product_dec from tb_spctItem ";
			SQLiteDatabase db = dbHelper.getReadableDatabase();
			Cursor c = db.rawQuery(sql, null);

			ShoppingCartItemData newsItem = null;

			while (c.moveToNext()) {
				newsItem = new ShoppingCartItemData();

				long product_id = c.getLong(0);
				String iconurl = c.getString(1);
				String product_name = c.getString(2);
				double product_price = c.getDouble(3);
				int product_num = c.getInt(4);
				String product_dec = c.getString(5);

				newsItem.setProduct_id(product_id);
				newsItem.setIconUrl(iconurl);
				newsItem.setProduct_name(product_name);
				newsItem.setProduct_price(product_price);
				newsItem.setProduct_num(product_num);
				newsItem.setProduct_dec(product_dec);
				newsItems.add(newsItem);
			}
			c.close();
			db.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return newsItems;

	}
}
